﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using System.Threading;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class Partita : PhoneApplicationPage
    {
        private static string key = "user";

        //storage dell'applicazionw
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private int idMatch; //id della partita
        private Utente player1; //giocatore locale
        private int player2; //id giocatore remoto
        private string player2name; //nome giocatore remoto
        private Mazzo deckp1; //deck giocatore locale
        private Tupla[,] grid; //griglia di gioco
        private int turn; //turno
        private Button clickedDeck; //carta selezionata dal mazzo
        private Carta cardToUpdate; //carta da updatare a ogni turno dell'avversario
        private int idCardToUpdate; //usato da getCarta
        private int caselleg1; //usato per calcolare vincitore
        private int caselleg2; //usato per calcolare vincitore
        private List<Button> gridButtons; //bottoni della griglia
        private List<Canvas> allCanvas; //tutti i canvas
        private List<Border> allBorders; //tutti i bordi
        private int xcardtoupdate; //usato in getcard
        private int ycardtoupdate; //usato in getcard

        private System.Windows.Threading.DispatcherTimer dispatcherTimer;
        private System.Windows.Threading.DispatcherTimer timeleft;

        private Style borderTopStyle = Application.Current.Resources["NumberTOP"] as Style;
        private Style borderBottomStyle = Application.Current.Resources["NumberBOT"] as Style;
        private Style borderLeftStyle = Application.Current.Resources["NumberLEFT"] as Style;
        private Style borderRightStyle = Application.Current.Resources["NumberRIGHT"] as Style;
        private Style numbersStyle = Application.Current.Resources["NumberPower"] as Style;

        public Partita()
        {
            InitializeComponent();

            string temp = (string)appSettings["matchId"];
            idMatch = Convert.ToInt32(temp);
            player1 = appSettings[key] as Utente;
            player2 = (int) appSettings["idplayer2"];
            player2name = (string) appSettings["nameplayer2"];
            deckp1 = appSettings["mydeck"] as Mazzo;
            turn = (int) appSettings["turn"];
            appSettings.Remove("matchId");
            appSettings.Remove("idplayer2");
            appSettings.Remove("nameplayer2");
            appSettings.Remove("mydeck");
            appSettings.Remove("turn");
     
            clickedDeck = null;

            textBlockPlayer2Name.Text = player2name;

            gridButtons = new List<Button>();
            gridButtons.Add(Griglia00);
            gridButtons.Add(Griglia01);
            gridButtons.Add(Griglia02);
            gridButtons.Add(Griglia10);
            gridButtons.Add(Griglia11);
            gridButtons.Add(Griglia12);
            gridButtons.Add(Griglia20);
            gridButtons.Add(Griglia21);
            gridButtons.Add(Griglia22);

            allCanvas = new List<Canvas>();
            allCanvas.Add(CanvasMazzo0);
            allCanvas.Add(CanvasMazzo1);
            allCanvas.Add(CanvasMazzo2);
            allCanvas.Add(CanvasMazzo3);
            allCanvas.Add(CanvasMazzo4);
            allCanvas.Add(CanvasGriglia00);
            allCanvas.Add(CanvasGriglia01);
            allCanvas.Add(CanvasGriglia02);
            allCanvas.Add(CanvasGriglia10);
            allCanvas.Add(CanvasGriglia11);
            allCanvas.Add(CanvasGriglia12);
            allCanvas.Add(CanvasGriglia20);
            allCanvas.Add(CanvasGriglia21);
            allCanvas.Add(CanvasGriglia22);

            allBorders = new List<Border>();
            allBorders.Add(BorderMazzo0);
            allBorders.Add(BorderMazzo1);
            allBorders.Add(BorderMazzo2);
            allBorders.Add(BorderMazzo3);
            allBorders.Add(BorderMazzo4);
            allBorders.Add(BorderGriglia00);
            allBorders.Add(BorderGriglia01);
            allBorders.Add(BorderGriglia02);
            allBorders.Add(BorderGriglia10);
            allBorders.Add(BorderGriglia11);
            allBorders.Add(BorderGriglia12);
            allBorders.Add(BorderGriglia20);
            allBorders.Add(BorderGriglia21);
            allBorders.Add(BorderGriglia22);

            this.grid = new Tupla[3, 3];//inizializzo la griglia
            for (int x = 0; x < 3; x++)
            {
                for (int y = 0; y < 3; y++)
                    grid[x, y] = new Tupla(0, Carta.NullSingleton);
            } 

            //inizializzo il mazzo visivamente
            var brush1 = new ImageBrush();
            Uri imageuri1 = new Uri((deckp1.getCarta(0).getImg()),UriKind.Relative);
            brush1.ImageSource = new BitmapImage(imageuri1);
            BorderMazzo0.Background = brush1;
            Border bordertop1 = new Border();
            bordertop1.Style = borderTopStyle;
            Border borderbottom1 = new Border();
            borderbottom1.Style = borderBottomStyle;
            Border borderleft1 = new Border();
            borderleft1.Style = borderLeftStyle;
            Border borderright1 = new Border();
            borderright1.Style = borderRightStyle;
            TextBlock numbertop1 = new TextBlock();
            numbertop1.Style = numbersStyle;
            numbertop1.Text = deckp1.getCarta(0).getTop().ToString();
            TextBlock numberbottom1 = new TextBlock();
            numberbottom1.Style = numbersStyle;
            numberbottom1.Text = deckp1.getCarta(0).getBottom().ToString();
            TextBlock numberleft1 = new TextBlock();
            numberleft1.Style = numbersStyle;
            numberleft1.Text = deckp1.getCarta(0).getLeft().ToString();
            TextBlock numberright1 = new TextBlock();
            numberright1.Style = numbersStyle;
            numberright1.Text = deckp1.getCarta(0).getRight().ToString();
            bordertop1.Child = numbertop1;
            borderbottom1.Child = numberbottom1;
            borderleft1.Child = numberleft1;
            borderright1.Child = numberright1;
            CanvasMazzo0.Children.Add(bordertop1);
            CanvasMazzo0.Children.Add(borderbottom1);
            CanvasMazzo0.Children.Add(borderleft1);
            CanvasMazzo0.Children.Add(borderright1);

            var brush2 = new ImageBrush();
            Uri imageuri2 = new Uri((deckp1.getCarta(1).getImg()),UriKind.Relative);
            brush2.ImageSource = new BitmapImage(imageuri2);
            BorderMazzo1.Background = brush2;
            Border bordertop2 = new Border();
            bordertop2.Style = borderTopStyle;
            Border borderbottom2 = new Border();
            borderbottom2.Style = borderBottomStyle;
            Border borderleft2 = new Border();
            borderleft2.Style = borderLeftStyle;
            Border borderright2 = new Border();
            borderright2.Style = borderRightStyle;
            TextBlock numbertop2 = new TextBlock();
            numbertop2.Style = numbersStyle;
            numbertop2.Text = deckp1.getCarta(1).getTop().ToString();
            TextBlock numberbottom2 = new TextBlock();
            numberbottom2.Style = numbersStyle;
            numberbottom2.Text = deckp1.getCarta(1).getBottom().ToString();
            TextBlock numberleft2 = new TextBlock();
            numberleft2.Style = numbersStyle;
            numberleft2.Text = deckp1.getCarta(1).getLeft().ToString();
            TextBlock numberright2 = new TextBlock();
            numberright2.Style = numbersStyle;
            numberright2.Text = deckp1.getCarta(1).getRight().ToString();
            bordertop2.Child = numbertop2;
            borderbottom2.Child = numberbottom2;
            borderleft2.Child = numberleft2;
            borderright2.Child = numberright2;
            CanvasMazzo1.Children.Add(bordertop2);
            CanvasMazzo1.Children.Add(borderbottom2);
            CanvasMazzo1.Children.Add(borderleft2);
            CanvasMazzo1.Children.Add(borderright2);

            var brush3 = new ImageBrush();
            Uri imageuri3 = new Uri((deckp1.getCarta(2).getImg()),UriKind.Relative);
            brush3.ImageSource = new BitmapImage(imageuri3);
            BorderMazzo2.Background = brush3;
            Border bordertop3 = new Border();
            bordertop3.Style = borderTopStyle;
            Border borderbottom3 = new Border();
            borderbottom3.Style = borderBottomStyle;
            Border borderleft3 = new Border();
            borderleft3.Style = borderLeftStyle;
            Border borderright3 = new Border();
            borderright3.Style = borderRightStyle;
            TextBlock numbertop3 = new TextBlock();
            numbertop3.Style = numbersStyle;
            numbertop3.Text = deckp1.getCarta(2).getTop().ToString();
            TextBlock numberbottom3 = new TextBlock();
            numberbottom3.Style = numbersStyle;
            numberbottom3.Text = deckp1.getCarta(2).getBottom().ToString();
            TextBlock numberleft3 = new TextBlock();
            numberleft3.Style = numbersStyle;
            numberleft3.Text = deckp1.getCarta(2).getLeft().ToString();
            TextBlock numberright3 = new TextBlock();
            numberright3.Style = numbersStyle;
            numberright3.Text = deckp1.getCarta(2).getRight().ToString();
            bordertop3.Child = numbertop3;
            borderbottom3.Child = numberbottom3;
            borderleft3.Child = numberleft3;
            borderright3.Child = numberright3;
            CanvasMazzo2.Children.Add(bordertop3);
            CanvasMazzo2.Children.Add(borderbottom3);
            CanvasMazzo2.Children.Add(borderleft3);
            CanvasMazzo2.Children.Add(borderright3);

            var brush4 = new ImageBrush();
            Uri imageuri4 = new Uri((deckp1.getCarta(3).getImg()),UriKind.Relative);
            brush4.ImageSource = new BitmapImage(imageuri4);
            BorderMazzo3.Background = brush4;
            Border bordertop4 = new Border();
            bordertop4.Style = borderTopStyle;
            Border borderbottom4 = new Border();
            borderbottom4.Style = borderBottomStyle;
            Border borderleft4 = new Border();
            borderleft4.Style = borderLeftStyle;
            Border borderright4 = new Border();
            borderright4.Style = borderRightStyle;
            TextBlock numbertop4 = new TextBlock();
            numbertop4.Style = numbersStyle;
            numbertop4.Text = deckp1.getCarta(3).getTop().ToString();
            TextBlock numberbottom4 = new TextBlock();
            numberbottom4.Style = numbersStyle;
            numberbottom4.Text = deckp1.getCarta(3).getBottom().ToString();
            TextBlock numberleft4 = new TextBlock();
            numberleft4.Style = numbersStyle;
            numberleft4.Text = deckp1.getCarta(3).getLeft().ToString();
            TextBlock numberright4 = new TextBlock();
            numberright4.Style = numbersStyle;
            numberright4.Text = deckp1.getCarta(3).getRight().ToString();
            bordertop4.Child = numbertop4;
            borderbottom4.Child = numberbottom4;
            borderleft4.Child = numberleft4;
            borderright4.Child = numberright4;
            CanvasMazzo3.Children.Add(bordertop4);
            CanvasMazzo3.Children.Add(borderbottom4);
            CanvasMazzo3.Children.Add(borderleft4);
            CanvasMazzo3.Children.Add(borderright4);

            var brush5 = new ImageBrush();
            Uri imageuri5 = new Uri((deckp1.getCarta(4).getImg()), UriKind.Relative);
            brush5.ImageSource = new BitmapImage(imageuri5);
            BorderMazzo4.Background = brush5;
            Border bordertop5 = new Border();
            bordertop5.Style = borderTopStyle;
            Border borderbottom5 = new Border();
            borderbottom5.Style = borderBottomStyle;
            Border borderleft5 = new Border();
            borderleft5.Style = borderLeftStyle;
            Border borderright5 = new Border();
            borderright5.Style = borderRightStyle;
            TextBlock numbertop5 = new TextBlock();
            numbertop5.Style = numbersStyle;
            numbertop5.Text = deckp1.getCarta(4).getTop().ToString();
            TextBlock numberbottom5 = new TextBlock();
            numberbottom5.Style = numbersStyle;
            numberbottom5.Text = deckp1.getCarta(4).getBottom().ToString();
            TextBlock numberleft5 = new TextBlock();
            numberleft5.Style = numbersStyle;
            numberleft5.Text = deckp1.getCarta(4).getLeft().ToString();
            TextBlock numberright5 = new TextBlock();
            numberright5.Style = numbersStyle;
            numberright5.Text = deckp1.getCarta(4).getRight().ToString();
            bordertop5.Child = numbertop5;
            borderbottom5.Child = numberbottom5;
            borderleft5.Child = numberleft5;
            borderright5.Child = numberright5;
            CanvasMazzo4.Children.Add(bordertop5);
            CanvasMazzo4.Children.Add(borderbottom5);
            CanvasMazzo4.Children.Add(borderleft5);
            CanvasMazzo4.Children.Add(borderright5);

            dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 5);

            timeleft = new System.Windows.Threading.DispatcherTimer();
            timeleft.Tick += new EventHandler(timeleft_Tick);
            timeleft.Interval = new TimeSpan(0, 0, 1);
            timeleft.Start();

            if (turn == player2)
            {
                caselleg1 = 1;
                caselleg2 = 0;
                foreach (Button b in gridButtons)
                {
                    b.IsEnabled = false;
                }
                dispatcherTimer.Start();
            }
            else
            {
                caselleg1 = 0;
                caselleg2 = 1;
            }    


        }//costruttore


        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getMatch.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetMatch), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }

            if (turn == player1.getId())
            {
                foreach (Button b in gridButtons)
                {
                    b.IsEnabled = true;
                }
                dispatcherTimer.Stop();
                timeleft.Start();
            }
        }

        private void timeleft_Tick(object sender, EventArgs e)
        {
            if (Convert.ToInt32(textBlockTimer.Text) == 0)
            {
                timeleft.Stop();
                if (turn == player1.getId()) //se sono rimasto inattivo esco e ho perso
                {
                    MessageBox.Show("You have been inactive for too long and lost the match. You'll now be returned to main menu.");

                    //Ho perso e mi tolgo i punti
                    player1.setPoints(player1.getPoints() - 20);
                    if (player1.getPoints() < 0){
                        player1.setPoints(0);
                    }

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserDefeat.php");
                        HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        loginRequest.Method = "POST";
                        loginRequest.ContentType = "application/x-www-form-urlencoded";
                        loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);

                        Uri myDBuri2 = new Uri("http://www.tripletriad.altervista.org/deleteMatch.php");
                        HttpWebRequest loginRequest2 = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        loginRequest2.Method = "POST";
                        loginRequest2.ContentType = "application/x-www-form-urlencoded";
                        loginRequest2.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackDeleteMatch), loginRequest2);
                    }
                    else
                    {
                        MessageBox.Show("Connection error, please retry later.");
                    }
                }
                else //se il mio avversario è rimasto inattivo mi assegno i punti della vittoria e esco
                {
                    dispatcherTimer.Stop();
                    timeleft.Stop();

                    player1.setPoints(player1.getPoints() + 50);

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserVictory.php");
                        HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        loginRequest.Method = "POST";
                        loginRequest.ContentType = "application/x-www-form-urlencoded";
                        loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                    }
                    else
                    {
                        MessageBox.Show("Connection error, please retry later.");
                    }

                    MessageBox.Show("You won because " + player2name + " has been inactive for 1 minute. You'll now be returned to main menu.");

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        Uri myDBuri2 = new Uri("http://www.tripletriad.altervista.org/deleteMatch.php");
                        HttpWebRequest loginRequest2 = (HttpWebRequest)HttpWebRequest.Create(myDBuri2);
                        loginRequest2.Method = "POST";
                        loginRequest2.ContentType = "application/x-www-form-urlencoded";
                        loginRequest2.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackDeleteMatch), loginRequest2);
                    }
                    else
                    {
                        MessageBox.Show("Connection error, please retry later.");
                    }
                }
            }
            else
            {
                textBlockTimer.Text = Convert.ToString(Convert.ToInt32(textBlockTimer.Text) - 1);
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult mRes = MessageBox.Show("You will lose if you exit now. Are you sure you want to retire?", "Exit", MessageBoxButton.OKCancel);
            if (mRes == MessageBoxResult.OK)
            {
                dispatcherTimer.Stop();
                timeleft.Stop();

                //Ho perso e mi tolgo i punti
                player1.setPoints(player1.getPoints() - 20);
                if (player1.getPoints() < 0)
                {
                    player1.setPoints(0);
                }

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserDefeat.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);

                    //elimino la partita dal db così che il mio avversario se ne accorga
                    Uri myDBuri2 = new Uri("http://www.tripletriad.altervista.org/deleteMatch.php");
                    HttpWebRequest loginRequest2 = (HttpWebRequest)HttpWebRequest.Create(myDBuri2);
                    loginRequest2.Method = "POST";
                    loginRequest2.ContentType = "application/x-www-form-urlencoded";
                    loginRequest2.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackDeleteMatch), loginRequest2);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
            if (mRes == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
            }
        }


        private void Mazzo_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;

            if (clickedDeck == null) //sto cliccando la prima carta
            {
                //seleziono la carta
                clickedDeck = button;
                Canvas parent = clickedDeck.Parent as Canvas;
                Canvas.SetZIndex(parent, 1);
            }
            else if (clickedDeck != null) //sto cliccando un'altra carta
            {
                //deseleziono la prima carta

                //seleziono la seconda
                Canvas parent = clickedDeck.Parent as Canvas;
                Canvas.SetZIndex(parent, 0);
                clickedDeck = button;
                parent = clickedDeck.Parent as Canvas;
                Canvas.SetZIndex(parent, 1);
                
            }
            else //sto ricliccando la carta
            {
                //Deseleziono la carta
                clickedDeck = null;
                
            }

        }//Mazzo_Click

        private void Griglia_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            string buttonname = button.Name;

            if (clickedDeck == null) //non avevo selezionato una carta dal mazzo
            {
                MessageBox.Show("Select a card from your deck");
            }
            else //avevo selezionato una carta
            {
                timeleft.Stop();
                button.IsEnabled = false;
                textBlockTimer.Text = "68";

                int x = int.Parse(buttonname.Substring(7, 1)); //indice x del bottone cliccato
                int y = int.Parse(buttonname.Substring(8, 1)); //indice y del bottone cliccato               
                
                int selectedfromdeck = int.Parse(clickedDeck.Name.Substring(5, 1)); //indice della carta selezionata nel mazzo
                Carta sel = deckp1.getCarta(selectedfromdeck); //carta selezionata dal mazzo

                grid[x, y].setOwner(player1.getId());//setto la carta e il proprietario della casella
                grid[x, y].setCard(sel);

                string bordername = "BorderGriglia" + x.ToString() + y.ToString();
                foreach (Border b in allBorders) //carta aggiunta visivamente alla griglia
                {
                    if (b.Name == bordername)
                    {
                        var brushgrid = new ImageBrush(); 
                        Uri imageurigrid = new Uri(sel.getImg(), UriKind.Relative);
                        brushgrid.ImageSource = new BitmapImage(imageurigrid);
                        b.Background = brushgrid;
                        setBorderColor((Border)b);
                    }
                }

                Canvas parentcanvasgrid = button.Parent as Canvas; //aggiungo i punti alla griglia
                Border bordertop = new Border();
                bordertop.Style = borderTopStyle;
                Border borderbottom = new Border();
                borderbottom.Style = borderBottomStyle;
                Border borderleft = new Border();
                borderleft.Style = borderLeftStyle;
                Border borderright = new Border();
                borderright.Style = borderRightStyle;
                TextBlock numbertop = new TextBlock();
                numbertop.Style = numbersStyle;
                numbertop.Text = sel.getTop().ToString();
                TextBlock numberbottom = new TextBlock();
                numberbottom.Style = numbersStyle;
                numberbottom.Text = sel.getBottom().ToString();
                TextBlock numberleft = new TextBlock();
                numberleft.Style = numbersStyle;
                numberleft.Text = sel.getLeft().ToString();
                TextBlock numberright = new TextBlock();
                numberright.Style = numbersStyle;
                numberright.Text = sel.getRight().ToString();
                bordertop.Child = numbertop;
                borderbottom.Child = numberbottom;
                borderleft.Child = numberleft;
                borderright.Child = numberright;
                parentcanvasgrid.Children.Add(bordertop);
                parentcanvasgrid.Children.Add(borderbottom);
                parentcanvasgrid.Children.Add(borderleft);
                parentcanvasgrid.Children.Add(borderright);

                Canvas parentdeckcanvas = clickedDeck.Parent as Canvas; //elimino la carta dal mazzo visivamente
                parentdeckcanvas.Visibility=System.Windows.Visibility.Collapsed;
                    
                clickedDeck = null;
            
                gridButtons.Remove(button);//rimuovo il bottone della griglia dove ho messo la carta
                //controllo se la carta appena messa ha effetto sulle carte vicine
                MakeMove(x, y, sel);
            }
        }//Griglia_Click


        public void MakeMove(int x, int y, Carta selected) //indici della casella selezionata, carta selezionata e giocatore che compie la mossa
        {
            switch (x)
            {
                case 0:
                    if (y == 0) //00
                    {
                        if (!grid[0, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 1].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[0, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia01);
                            }
                        }
                        if (!grid[1, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 0].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[1, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia10);
                            }
                        }
                     
                        break;
                    }
                    else if (y == 1) //01
                    {
                        if (!grid[0, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 0].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[0, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia00);
                            }
                        }
                        if (!grid[0, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 2].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[0, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia02);
                            }
                        }
                        if (!grid[1, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 1].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[1, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia11);
                            }
                        }
                        break;
                    }
                    else //02
                    {
                        if (!grid[0, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 1].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[0, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia01);
                            }
                        }
                        if (!grid[1, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 2].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[1, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia12);
                            }
                        }
                        break;
                    }
                case 1:
                    if (y == 0) //10
                    {
                        if (!grid[0, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 0].getCard();
                            if (c.getBottom() < selected.getTop())
                            {
                                grid[0, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia00);
                            }
                        }
                        if (!grid[1, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 1].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[1, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia11);
                            }
                        }
                        if (!grid[2, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 0].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[2, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia20);
                            }
                        }
                        break;
                    }
                    else if (y == 1) //11
                    {
                        if (!grid[0, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 1].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[0, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia01);
                            }
                        }
                        if (!grid[1, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 0].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[1, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia10);
                            }
                        }
                        if (!grid[1, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 2].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[1, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia12);
                            }
                        }
                        if (!grid[2, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 1].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[2, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia21);
                            }
                        }
                        break;
                    }
                    else //12
                    {
                        if (!grid[0, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[0, 2].getCard();
                            if (c.getBottom() < selected.getTop())
                            {
                                grid[0, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia02);
                            }
                        }
                        if (!grid[1, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 1].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[1, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia11);
                            }
                        }
                        if (!grid[2, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 2].getCard();
                            if (c.getTop() < selected.getBottom())
                            {
                                grid[2, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia22);
                            }
                        }
                        break;
                    }
                case 2:
                    if (y == 0) //20
                    {
                        if (!grid[1, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 0].getCard();
                            if (c.getBottom() < selected.getTop())
                            {
                                grid[1, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia10);
                            }
                        }
                        if (!grid[2, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 1].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[2, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia21);
                            }
                        }
                        break;
                    }
                    else if (y == 1) //21
                    {
                        if (!grid[2, 0].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 0].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[2, 0].setOwner(player1.getId());
                                setBorderColor(BorderGriglia20);
                            }
                        }
                        if (!grid[1, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 1].getCard();
                            if (c.getBottom() < selected.getTop())
                            {
                                grid[1, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia11);
                            }
                        }
                        if (!grid[2, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 2].getCard();
                            if (c.getLeft() < selected.getRight())
                            {
                                grid[2, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia22);
                            }
                        }
                        break;
                    }
                    else //22
                    {
                        if (!grid[1, 2].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[1, 2].getCard();
                            if (c.getBottom() < selected.getTop())
                            {
                                grid[1, 2].setOwner(player1.getId());
                                setBorderColor(BorderGriglia12);
                            }
                        }
                        if (!grid[2, 1].getCard().Equals(Carta.NullSingleton))
                        {
                            Carta c = grid[2, 1].getCard();
                            if (c.getRight() < selected.getLeft())
                            {
                                grid[2, 1].setOwner(player1.getId());
                                setBorderColor(BorderGriglia21);
                            }
                        }
                        break;
                    }
            }

            turn = player2;

            foreach (Button b in gridButtons)
            {
                b.IsEnabled = false;
            }

            if (NetworkInterface.GetIsNetworkAvailable())
            {
                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateMatch.php");
                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                loginRequest.Method = "POST";
                loginRequest.ContentType = "application/x-www-form-urlencoded";
                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateMatch), loginRequest);
            }
            else
            {
                MessageBox.Show("Connection error, please retry later.");
            }

            bool finita = true;
            //gestisco la fine della partita nel caso abbia fatto io l'ultima mossa
            foreach (Tupla t in grid)
            {
                if (t.getOwner() == 0)
                {
                    finita = false;
                    break;
                }
            }
            if (finita)
            {
                dispatcherTimer.Stop();
                timeleft.Stop();
                foreach (Tupla t in grid)
                {
                    if (t.getOwner() == player1.getId())
                    {
                        caselleg1++;
                    }
                    else
                    {
                        caselleg2++;
                    }
                }
                if (caselleg1 == caselleg2)
                {
                    MessageBox.Show("Draw");
                }
                else if (caselleg1 < caselleg2)
                {
                    MessageBox.Show(player2name + " won");

                    player1.setPoints(player1.getPoints() - 20);
                    if (player1.getPoints() < 0)
                    {
                        player1.setPoints(0);
                    }

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserDefeat.php");
                        HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        loginRequest.Method = "POST";
                        loginRequest.ContentType = "application/x-www-form-urlencoded";
                        loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                    }
                    else
                    {
                        MessageBox.Show("Connection error, please retry later.");
                    }
                }
                else
                {
                    MessageBox.Show(player1.getUsername() + " won");

                    player1.setPoints(player1.getPoints() + 50);

                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserVictory.php");
                        HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                        loginRequest.Method = "POST";
                        loginRequest.ContentType = "application/x-www-form-urlencoded";
                        loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                    }
                    else
                    {
                        MessageBox.Show("Connection error, please retry later.");
                    }
                }

                NavigationService.Navigate(new Uri("/MainPage.xaml",UriKind.Relative));
            }
            else
            {
                timeleft.Start();
                dispatcherTimer.Start();
            }
        }//MakeMove

        private void setBorderColor(Border b)
        {
            string bordername = b.Name;
            int x = int.Parse(bordername.Substring(13, 1)); //indice x del bottone cliccato
            int y = int.Parse(bordername.Substring(14, 1)); //indice y del bottone cliccato
            if (grid[x,y].getOwner() == player1.getId())
            {
                b.BorderBrush = new SolidColorBrush(Colors.Blue);
            }
            else if (grid[x,y].getOwner() == player2)
            {
                b.BorderBrush = new SolidColorBrush(Colors.Red);
            }
        }

        private void GetRequestStreamCallbackUpdateMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + idMatch.ToString() + "&turno=" + turn.ToString() +
                "&c00=" + grid[0, 0].getCard().getId().ToString() + "&g00=" + grid[0, 0].getOwner().ToString() +
                "&c01=" + grid[0, 1].getCard().getId().ToString() + "&g01=" + grid[0, 1].getOwner().ToString() +
                "&c02=" + grid[0, 2].getCard().getId().ToString() + "&g02=" + grid[0, 2].getOwner().ToString() +
                "&c10=" + grid[1, 0].getCard().getId().ToString() + "&g10=" + grid[1, 0].getOwner().ToString() +
                "&c11=" + grid[1, 1].getCard().getId().ToString() + "&g11=" + grid[1, 1].getOwner().ToString() +
                "&c12=" + grid[1, 2].getCard().getId().ToString() + "&g12=" + grid[1, 2].getOwner().ToString() +
                "&c20=" + grid[2, 0].getCard().getId().ToString() + "&g20=" + grid[2, 0].getOwner().ToString() +
                "&c21=" + grid[2, 1].getCard().getId().ToString() + "&g21=" + grid[2, 1].getOwner().ToString() +
                "&c22=" + grid[2, 2].getCard().getId().ToString() + "&g22=" + grid[2, 2].getOwner().ToString();
            
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackUpdateMatch), myRequest);
        }//GetRequestStreamCallbackUpdateMatch

        private void GetResponsetStreamCallbackUpdateMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingUpdateMatch(result));
            }
        }//GetResponsetStreamCallbackUpdateMatch

        private void ParsingUpdateMatch(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
        }//ParsingUpdateMatch

        private void GetRequestStreamCallbackGetMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + idMatch.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGetMatch), myRequest);
        }//GetRequestStreamCallbackGetMatch

        private void GetResponsetStreamCallbackGetMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGetMatch(result));
            }
        }//GetResponsetStreamCallbackGetMatch

        private void ParsingGetMatch(string result)
        {
            string[] ris = majorSplit(result);

            if (result == "")
            {
                //il mio avversario ha abbandonato quindi mi assegno i punti della vittoria ed esco
                dispatcherTimer.Stop();
                timeleft.Stop();

                player1.setPoints(player1.getPoints() + 50);

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserVictory.php");
                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    loginRequest.Method = "POST";
                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }

                MessageBox.Show("You won because " + player2name + " left the match. You'll now be returned to main menu.");
                NavigationService.Navigate(new Uri("/MainPage.xaml",UriKind.Relative));
            }
            else 
            {
                string[] dati = minorSplit(ris[0]);
                turn = Convert.ToInt32(dati[3]);
                int k = 4; //indice della carta
                int z = 5; //indice del giocatore
                for (int i = 0; i < 3; i++) //aggiorno la tabella con i dati dal server
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (grid[i, j].getCard().getId() != Convert.ToInt32(dati[k])) //se la carta in quella posizione è cambiata, il player 2 ne ha messa una nuova e la prendo dal server
                        {
                            timeleft.Stop(); //il mio avversario ha fatto la sua mossa
                            textBlockTimer.Text = "60";

                            //update della carta nuova
                            idCardToUpdate = Convert.ToInt32(dati[k]);
                            xcardtoupdate = i;
                            ycardtoupdate = j;

                            if (NetworkInterface.GetIsNetworkAvailable())
                            {
                                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/getCard.php");
                                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                                loginRequest.Method = "POST";
                                loginRequest.ContentType = "application/x-www-form-urlencoded";
                                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackGetCard), loginRequest);
                            }
                            else
                            {
                                MessageBox.Show("Connection error, please retry later.");
                            }
                            
                        }
                        grid[i, j].setOwner(Convert.ToInt32(dati[z]));
                        string bordername = "BorderGriglia" + i.ToString() + j.ToString();
                        foreach (Border b in allBorders)
                        {
                            if (b.Name == bordername)
                            {
                                setBorderColor(b);
                            }
                        }

                        k += 2; //aumento gli indici
                        z += 2;
                    }
                }
            }
        }//ParsingGetMatch

        private void GetRequestStreamCallbackGetCard(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&id=" + idCardToUpdate.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackGetCard), myRequest);
        }//GetRequestStreamCallbackGetCard

        private void GetResponsetStreamCallbackGetCard(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingGetCard(result));
            }
        }//GetResponsetStreamGetCard

        private void ParsingGetCard(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else
            {
                string[] dati = minorSplit(ris[0]);
                int cardId = Convert.ToInt32(dati[0]);
                string image = dati[1]; ;
                string name = dati[2];
                int top = Convert.ToInt32(dati[3]);
                int bottom = Convert.ToInt32(dati[4]);
                int left = Convert.ToInt32(dati[5]);
                int right = Convert.ToInt32(dati[6]);
                int level = Convert.ToInt32(dati[7]);
                int cost = Convert.ToInt32(dati[8]);
                cardToUpdate = new Carta(cardId, name, image, top, bottom, left, right, cost, level);

                grid[xcardtoupdate, ycardtoupdate].setCard(cardToUpdate);
                string bordername = "BorderGriglia" + xcardtoupdate.ToString() + ycardtoupdate.ToString();
                foreach (Border b in allBorders) //carta aggiunta visivamente alla griglia
                {
                    if (b.Name == bordername)
                    {
                        var brushgrid = new ImageBrush();
                        Uri imageurigrid = new Uri(image, UriKind.Relative);
                        brushgrid.ImageSource = new BitmapImage(imageurigrid);
                        b.Background = brushgrid;
                    }
                }

                string canvasname = "CanvasGriglia" + xcardtoupdate.ToString() + ycardtoupdate.ToString();
                foreach (Canvas c in allCanvas) //carta aggiunta visivamente alla griglia
                {
                    if (c.Name == canvasname)
                    {
                        Border bordertop = new Border();
                        bordertop.Style = borderTopStyle;
                        Border borderbottom = new Border();
                        borderbottom.Style = borderBottomStyle;
                        Border borderleft = new Border();
                        borderleft.Style = borderLeftStyle;
                        Border borderright = new Border();
                        borderright.Style = borderRightStyle;
                        TextBlock numbertop = new TextBlock();
                        numbertop.Style = numbersStyle;
                        numbertop.Text = top.ToString();
                        TextBlock numberbottom = new TextBlock();
                        numberbottom.Style = numbersStyle;
                        numberbottom.Text = bottom.ToString();
                        TextBlock numberleft = new TextBlock();
                        numberleft.Style = numbersStyle;
                        numberleft.Text = left.ToString();
                        TextBlock numberright = new TextBlock();
                        numberright.Style = numbersStyle;
                        numberright.Text = right.ToString();
                        bordertop.Child = numbertop;
                        borderbottom.Child = numberbottom;
                        borderleft.Child = numberleft;
                        borderright.Child = numberright;
                        c.Children.Add(bordertop);
                        c.Children.Add(borderbottom);
                        c.Children.Add(borderleft);
                        c.Children.Add(borderright);

                        //gestisco la fine della partita nel caso l'ultima mossa l'abbia fatta g2
                        bool finita = true;
                        foreach (Tupla t in grid)
                        {
                            if (t.getOwner() == 0)
                            {
                                finita = false;
                                break;
                            }
                        }
                        if (finita)
                        {
                            dispatcherTimer.Stop();
                            timeleft.Stop();
                            foreach (Tupla t in grid)
                            {
                                if (t.getOwner() == player1.getId())
                                {
                                    caselleg1++;
                                }
                                else
                                {
                                    caselleg2++;
                                }
                            }
                            if (caselleg1 == caselleg2)
                            {
                                MessageBox.Show("Draw");
                            }
                            else if (caselleg1 < caselleg2)
                            {
                                MessageBox.Show(player2name + " won");

                                player1.setPoints(player1.getPoints() - 20);
                                if (player1.getPoints() < 0)
                                {
                                    player1.setPoints(0);
                                }

                                if (NetworkInterface.GetIsNetworkAvailable())
                                {
                                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserDefeat.php");
                                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                                    loginRequest.Method = "POST";
                                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                                }
                                else
                                {
                                    MessageBox.Show("Connection error, please retry later.");
                                }
                            }
                            else
                            {
                                MessageBox.Show(player1.getUsername() + " won");

                                player1.setPoints(player1.getPoints() + 50);

                                if (NetworkInterface.GetIsNetworkAvailable())
                                {
                                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/updateUserVictory.php");
                                    HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                                    loginRequest.Method = "POST";
                                    loginRequest.ContentType = "application/x-www-form-urlencoded";
                                    loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackUpdateUserPoints), loginRequest);
                                }
                                else
                                {
                                    MessageBox.Show("Connection error, please retry later.");
                                }
                            }

                            //elimino la partita dal database
                            if (NetworkInterface.GetIsNetworkAvailable())
                            {
                                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/deleteMatch.php");
                                HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                                loginRequest.Method = "POST";
                                loginRequest.ContentType = "application/x-www-form-urlencoded";
                                loginRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackDeleteMatch), loginRequest);
                            }
                            else
                            {
                                MessageBox.Show("Connection error, please retry later.");
                            }
                        }
                    }
                }

                Button temp = new Button();
                foreach (Button b in gridButtons)
                {
                    if (b.Name == "Griglia" + xcardtoupdate.ToString() + ycardtoupdate.ToString())
                    {
                        b.IsEnabled = false;
                        temp = b;
                    }
                }
                gridButtons.Remove(temp);
            }
        }//ParsingGetCard

        private void GetRequestStreamCallbackDeleteMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + idMatch.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackDeleteMatch), myRequest);
        }//GetRequestStreamCallbackDeleteMatch

        private void GetResponsetStreamCallbackDeleteMatch(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingDeleteMatch(result));
            }
        }//GetResponsetStreamDeleteMatch

        private void ParsingDeleteMatch(string result)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml",UriKind.Relative));
        }//ParsingDeleteMatch

        private void GetRequestStreamCallbackUpdateUserPoints(IAsyncResult callbackResult)
        {
            Utente io = appSettings[key] as Utente;
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);
            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + player1.getId().ToString() + "&Points=" + player1.getPoints().ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackUpdateUserPoints), myRequest);
        }//GetRequestStreamCallbackUpdateUserVictory

        private void GetResponsetStreamCallbackUpdateUserPoints(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingUpdateUserPoints(result));
            }
        }//GetResponsetStreamCallbackUpdateUserVictory

        private void ParsingUpdateUserPoints(string result)
        {
            string[] ris = majorSplit(result);

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
        }//ParsingUpdateUserVictory

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
        
    }
}